package com.example.android.ouactivity.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.example.android.ouactivity.login_register.Login;
import com.example.android.ouactivity.model.User;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.content.Context.MODE_PRIVATE;
import static org.apache.http.util.EncodingUtils.getString;

/**
 * Created by 张瀚 on 2016/11/20.
 */

public class ReadUserInfo {
    private static Context context;
    private static String fileName;
    public ReadUserInfo(Context con,String fileName){
        this.context = con;
        this.fileName = fileName;
    }
    public void saveInfo(String info){
        FileOutputStream fos = null;
        try {
            fos = context.openFileOutput(fileName, MODE_PRIVATE);//获取文件输出流
            fos.write(info.getBytes());//保存用户名和密码
            fos.flush();   //清除缓存
            Log.i("sava:","success");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public String getInfo(){
        String result = "";
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = context.openFileInput(fileName);
            byte[] buffer = new byte[fileInputStream.available()];
            fileInputStream.read(buffer);
            result = new String(buffer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    public boolean deleteInfo(){
        return context.deleteFile(fileName);
    }
    public User getUserByFile(){
        User user = new User();
        String info = this.getInfo();
        user.setId(info.split(",")[0]);
        user.setName(info.split(",")[1]);
        user.setImage(info.split(",")[2]);
        return user;
    }
    public boolean hasFile(){
        if(this.getInfo().equals("")){
            return false;
        }else {
            return true;
        }
    }
}
